package com.wcl.hencodertest.test06_drawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ConvertUtils;

/**
 * @项目名： HenCoderTest
 * @包名： com.wcl.hencodertest.test06_drawing
 * @文件名: PieChart
 * @创建者: kilin
 * @创建时间: 2020/4/15 20:00
 * @描述： TODO
 */
public class PieChart extends View {

    public static final int RADIUS = ConvertUtils.dp2px(100);
    public static final int TRANSLATE_LENGTH = 20;

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    RectF rectF;

    float[] angles = {60, 50, 80, 10, 70, 90};
    int[] colors = {Color.YELLOW, Color.GREEN, Color.GRAY, Color.BLACK, Color.BLUE, Color.RED};


    public PieChart(Context context) {
        super(context);
    }

    public PieChart(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    {
        rectF = new RectF(getWidth() / 2 - RADIUS, getHeight() - RADIUS, getWidth() + RADIUS, getHeight() + RADIUS);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int currentAngle = 0;
        for (int i = 0; i < 6; i++) {
            paint.setColor(colors[i]);

            if (i == 5) {
                canvas.save();
                canvas.translate((float) (Math.cos(Math.toRadians(currentAngle + angles[i] / 2)) * TRANSLATE_LENGTH),
                        (float) (Math.sin(Math.toRadians(currentAngle + angles[i] / 2))) * TRANSLATE_LENGTH);
                currentAngle = drawArc(canvas, currentAngle, angles[i]);
                canvas.restore();
            } else {
                currentAngle = drawArc(canvas, currentAngle, angles[i]);
            }

        }
    }

    private int drawArc(Canvas canvas, int currentAngle, float angle) {
        canvas.drawArc(getWidth() / 2 - RADIUS,
                getHeight() / 2 - RADIUS,
                getWidth() / 2 + RADIUS,
                getHeight() / 2 + RADIUS,
                currentAngle,
                angle,
                true, paint);
        currentAngle += angle;
        return currentAngle;
    }
}
